<template>
  <div class="app-container">

    <div class="search-div">
      <el-form label-width="80px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单状态">
              <el-select v-model="searchObj.orderStatus" placeholder="订单状态">
                <el-option label="未接单" :value="1" />
                <el-option label="进行中" :value="2" />
                <el-option label="已完成" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户id">
              <el-input v-model="searchObj.uid" style="width: 95%" placeholder="用户id" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="fetchData()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px;"
    >

      <el-table-column
        label="序号"
        width="70"
        align="center"
      >
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="uname" label="用户名" width="200" />
      <el-table-column prop="pname" label="产品名" width="200">
        <template slot-scope="scope">
          {{ scope.row.pname.join(', ') }}
        </template>
      </el-table-column>
      <el-table-column prop="pcount" label="产品数量" width="200" />
      <el-table-column prop="orderTime" label="下单时间" width="250" />
      <el-table-column label="订单状态" width="200">
        <template slot-scope="scope">
          <div :style="getStatusStyle(scope.row.orderStatus)" class="centered-text">
            {{ getStatusText(scope.row.orderStatus) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" size="mini" title="删除" @click="removeDataById(scope.row.id)" />
          <el-button v-if="scope.row.orderStatus === 1" type="primary" size="mini" title="接单" @click="edit(scope.row.id)">
            接单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />
    <el-dialog title="接单" :visible.sync="dialogVisible" width="40%">
      <el-form ref="dataForm" :model="Order" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="订单ID">
          {{ Order.id }}
        </el-form-item>
        <!-- 显示用户ID -->
        <el-form-item label="用户ID">
          {{ Order.uid }}
        </el-form-item>

        <!-- 显示用户姓名 -->
        <el-form-item label="用户姓名">
          {{ Order.uname }}
        </el-form-item>
        <!-- 设备ID选择框 -->
        <el-form-item label="选择设备" prop="fdids">
          <el-checkbox-group v-model="startPlanVO.ids" @change="updateSelectedDeviceCount">
            <el-checkbox v-for="item in fdids" :key="item" :label="item" :name="item">设备{{ item }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="add(Order.id)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.centered-text {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 100%; /* 让内容占据整个单元格的高度 */
}
</style>

<script>
import api from '@/api/system/sysOrder'
const defaultForm = {
  id: '',
  pid: '',
  pcount: 0,
  orderStatus: '',
  orderTime: '',
  uid: '',
  uname: '',
  pname: '',
  ostatus: ''

}

const defaultForm1 = {
  Id: '',
  fname: '',
  fType: '',
  dcount: '',
  fImage: '',
  roleName: ''
}
const defaultForm2 = {
  id: '',
  ids: []
}

export default {
  data() {
    return {
      listLoading: true, // 数据是否正在加载
      list: null, // banner列表
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      records: 0,
      searchObj: {}, // 查询表单对象
      createTimes: [],

      dialogVisible: false,
      Order: defaultForm,
      Factory: defaultForm1,
      saveBtnDisabled: false,
      dialogRoleVisible: false,
      isIndeterminate: false, // 是否是不确定的
      checkAll: false, // 是否全选
      fdids: [],
      startPlanVO: defaultForm2,
      selectedDeviceCount: 0
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    console.log('list created......')
    this.fetchData()
  },

  // 生命周期函数：内存准备完毕，页面渲染成功
  mounted() {
    console.log('list mounted......')
  },

  methods: {
    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size)
      this.limit = size
      this.fetchData(1)
    },

    // 加载banner列表数据
    fetchData(page = 1) {
      this.page = page
      console.log('翻页。。。' + this.page)

      api.getPageList(this.page, this.limit, this.searchObj).then(
        response => {
          // this.list = response.data.list
          this.list = response.data.records
          this.total = response.data.total

          // 数据加载并绑定成功
          this.listLoading = false
        }
      )
    },

    // 重置查询表单
    resetData() {
      console.log('重置查询表单')
      this.searchObj = {}
      this.createTimes = []
      this.fetchData()
    },

    // 根据id删除数据
    removeDataById(id) {
      // debugger
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return api.removeById(id)
      }).then((response) => {
        this.fetchData(this.page)
        this.$message.success(response.message || '删除成功')
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    edit(id) {
      this.dialogVisible = true
      this.fetchDataById(id)
      this.fetchFreeById(id)
    },
    fetchFreeById(id) {
      api.selectFreeDevice(id).then(response => {
        this.fdids = response.data.fdids
      })
    },
    fetchDataById(id) {
      api.getById(id).then(response => {
        this.Order = response.data
      })
    },
    updateSelectedDeviceCount() {
      // 更新选中设备数量
      this.selectedDeviceCount = this.startPlanVO.ids.length
    },
    // -------------
    add(id) {
      this.dialogVisible = true
      // 确认操作时的逻辑
      api.selectFreeDevice(id).then(response => {
        if (this.selectedDeviceCount >= response.data.count) {
          // 处理订单
          this.confirmOrder()
        } else {
          // 提示选中的设备不足以处理订单
          this.$message.warning('选中的设备不足以处理订单')
        }
      })
    },
    confirmOrder() {
      this.startPlanVO.id = this.Order.id
      console.log(this.startPlanVO)
      this.saveData()
    },
    // 新增
    saveData() {
      api.startPlan(this.startPlanVO).then(response => {
        this.$message.success('操作成功')
        this.startPlanVO = {
          id: '',
          ids: [] // 重新初始化为默认值
        }
        this.dialogVisible = false
        console.log(this.startPlanVO)
        this.fetchData(this.page)
      })
    },

    showAssignRole(row) {
      this.Order = row
      this.dialogRoleVisible = true
      this.getRoles()
    },
    getStatusStyle(status) {
      let style = {}
      switch (status) {
        case 3:
          style = {
            background: 'linear-gradient(to right, #56ab2f, #a8e063)' // 绿色渐变背景
            // boxShadow: '0px 4px 14px rgba(86, 171, 47, 0.5)', // 绿色阴影
          }
          break
        case 2:
          style = {
            background: 'linear-gradient(to right, #f09819, #edde5d)' // 黄色渐变背景
            // boxShadow: '0px 4px 14px rgba(240, 152, 25, 0.5)', // 黄色阴影
          }
          break
        case 1:
          style = {
            background: 'linear-gradient(to right, #bdc3c7, #2c3e50)' // 灰色渐变背景
            // boxShadow: '0px 4px 14px rgba(189, 195, 199, 0.5)', // 灰色阴影
          }
          break
        default:
          break
      }
      return {
        ...style,
        color: 'white', // 文字颜色为白色
        padding: '5px 10px', // 添加一些填充效果
        borderRadius: '5px' // 圆角效果
      }
    },
    getStatusText(status) {
      switch (status) {
        case 1:
          return '未接单'
        case 2:
          return '进行中'
        case 3:
          return '已完成'
        default:
          return '未知'
      }
    }
  }
}
</script>
